package com.daigou.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.daigou.dto.AjaxResult;
import com.daigou.tools.UploadFileUtils;

/**
 * 
* 项目名称：monkey Maven Webapp   
* 类名称：ImageUploadController   
* 类描述：头像上传表示层   
* 创建人：李志   
* 创建时间：2017年01月22日  上午9:39:45
* 修改人：李志   
* 修改时间：2017年04月6日 下午10:25:13   
* @version    
*
 */
@Controller("imageUploadController")
@RequestMapping(value = "/admin")
public class ImageUploadController{
	
	private static Logger logger = LoggerFactory.getLogger(ImageUploadController.class);
		
    @RequestMapping(value = "/{code}/upload/{dir}",method = RequestMethod.POST)  
	@ResponseBody
	public AjaxResult uploadImage(@PathVariable("code")String code,@PathVariable("dir")String dir,
			@RequestParam("file")MultipartFile file,HttpServletRequest request){
    	AjaxResult ajaxResult = new AjaxResult(true);
		if (!file.isEmpty()) {
			try{
		        //判断文件的MIMEtype
		        String type = file.getContentType();
		        if(type == null || !type.toLowerCase().startsWith("image/")){
		        	ajaxResult.setSuccess(false);
		        	ajaxResult.setMessage("不支持的文件类型，仅支持图片!");
		        	return  ajaxResult;
		        }
		        String imagePathPrifix = code + File.separator + dir;
				//头像存放文件
		        String filePath = UploadFileUtils.upload(request,file, imagePathPrifix);
		        ajaxResult.setSuccess(true);
		        ajaxResult.setData(filePath.replace("\\", "/"));
	        	ajaxResult.setMessage("图片上传成功!");
	        	return ajaxResult;
			}catch(Exception e){
				logger.error("ImageUploadController.uploadHeadPortrait", e);
				ajaxResult.setSuccess(true);
	        	ajaxResult.setMessage(e.getMessage());
				return ajaxResult;
			}
		}
		ajaxResult.setSuccess(false);
    	ajaxResult.setMessage("请选择图片!");
		return ajaxResult;
	}
}
